<?php

/**
 * This is the model class for table "tbl_instrument_date".
 *
 * The followings are the available columns in table 'tbl_instrument_date':
 * @property integer $date_id
 * @property integer $enabled
 * @property integer $instrument_id
 * @property string $start_date
 * @property string $end_date
 *
 * The followings are the available model relations:
 * @property Instrument $instrument
 */
class InstrumentDate extends CActiveRecord
{
    const ENABLED_TRUE = 1;
    const ENABLED_FALSE = 0;

    const STATUS_UNENABLED = 0;
    const STATUS_ISENABLED = 1;
    const STATUS_ALREADY_OTHER = 2;
    const STATUS_ALREADY_MIME = 3;

    public $start_time;
    public $end_time;
    public function getEnabledLable()
    {
        return $this->enabled == self::ENABLED_TRUE ? '可预约' : '不可预约';
    }
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return InstrumentDate the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'tbl_instrument_date';
	}
	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('instrument_id, start_date, end_date,start_time, end_time', 'required'),
			array('enabled, instrument_id', 'numerical', 'integerOnly'=>true),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('date_id, enabled, instrument_id, start_date, end_date', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'instrument' => array(self::BELONGS_TO, 'Instrument', 'instrument_id'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'date_id' => 'Date',
			'enabled' => '是否可预约',
			'instrument_id' => 'Instrument',
			'start_date' => '开始日期',
			'end_date' => '结束日期',
            'start_time' => '每天开始时间',
			'end_time' => '每天结束时间',

		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search($iid)
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('date_id',$this->date_id);
		$criteria->compare('enabled',$this->enabled);
		$criteria->compare('instrument_id',$iid);
		$criteria->compare('start_date',$this->start_date,true);
		$criteria->compare('end_date',$this->end_date,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
  /**
     * ===============================================================
     *                  生成总时间表(只考虑可预定与不可预定)
     * ===============================================================
     */
   
    /**
     * 生成时间表
     * @args $id = instrument_id
     * @author : nonglei
     * @date   : 17/08/2014
     */
    public static function GenerateDateTableByID($id)
    {
        $instrumentModel = Instrument::model()->findByPk($id);
        $isEnabledDateList = $instrumentModel->isEnabledDate;
        if(count($isEnabledDateList) == 0)
        {
            //没有可预约时间
            return null;
        }
        //最小可预约时间
        $minDate = CDateTimeParser::parse('2030-01-01 12','yyyy-MM-dd hh');
        $maxDate = 0;
        foreach($isEnabledDateList as $elem)
        {
		    $start = CDateTimeParser::parse($elem->start_date,'yyyy-MM-dd hh:mm:ss');
		    $end = CDateTimeParser::parse($elem->end_date,'yyyy-MM-dd hh:mm:ss');
            if($start < $minDate)
            {
                $minDate = $start;
            }
            if($end > $maxDate)
            {
                $maxDate = $end;
            }
        }
        $minDate = strtotime(date('Y-m-d', $minDate));
        $maxDate = strtotime(date('Y-m-d', $maxDate));
        //向昨天找到最近的星期天
        $backDay = date('w',$minDate);
        $minDate = strtotime("- {$backDay} days", $minDate);
        //向明天找最近的星期天
        $forwardDay = 7 - date('w', $maxDate);
        $maxDate = strtotime("+ {$forwardDay} days", $maxDate);

        //获取当前可预约的时间数组
        $IsEnabledArray = InstrumentDate::getIsEnabledDateArray($id);
        $weekarray=array("天","一","二","三","四","五","六");
        $dateTable = array();
        //一周一周的处理
        for(; $minDate != $maxDate; $minDate = strtotime("+ 1 days", $minDate))
        {
            $week = array();
            $week['start_date'] = date('Y-m-d', $minDate);
            $minDate = strtotime("+ 6 days", $minDate);
            $week['end_date'] = date('Y-m-d', $minDate);
            //一天一天的处理
            for($i = 0; $i < 7; $i++)
            {
                $day = array();
                $day['date'] = date('Y-m-d', strtotime("+ {$i} days", strtotime($week['start_date'])));
                $day['day'] = '星期'.$weekarray[date('w', strtotime($day['date']))];
                //一个小时一个小时的处理
                for($j = 0; $j < 24; $j++)
                {
                    $today = date('Y-m-d H:i:s', strtotime("+ {$j} hours", strtotime($day['date'])));
                    $hour = 0;
                    if($IsEnabledArray[$today] == InstrumentDate::ENABLED_TRUE)
                    {
                        $hour = 1;
                    }
                    array_push($day, $hour);
                }
                array_push($week, $day);
            }
            array_push($dateTable, $week);
        }
        return $dateTable;
    }

    /**
     * 判断是否可以预约,用填表法
     * @args   : $id : instrument_id
     * @return : array('2014-08-17 22:00:00'=>1, '2014-08-17 22:00:00'=>0)
     * @author : nonglei
     * @date   : 17/08/2014
     */
    public static function getIsEnabledDateArray($id)
    {
        $resultArray = array();
        $model = Instrument::model()->findByPk($id);
        $isEnabledDateList = $model->isEnabledDate;
        if(count($isEnabledDateList) == 0)
        {
            //没有可预约时间
            return $resultArray;
        }
        foreach($isEnabledDateList as $elem)
        {
            $elem->start_time = date('H', strtotime($elem->start_date));
            $elem->end_time = date('H', strtotime($elem->end_date));
            $elem->start_date = date('Y-m-d', strtotime($elem->start_date));
            $elem->end_date = date('Y-m-d', strtotime($elem->end_date));

            $startDate = CDateTimeParser::parse($elem->start_date,'yyyy-MM-dd');
		    $endDate = CDateTimeParser::parse($elem->end_date,'yyyy-MM-dd');
            for(;$startDate <= $endDate;$startDate = strtotime("+ 1 days", $startDate))
            {
                $startTime = $elem->start_time;
                $startTime++;
                $startTime--;
                $endTime = $elem->end_time;;
                $endTime++;
                $endTime--;
                for(;$startTime != $endTime && $startTime < 24;$startTime++)
                {
                    $val = date('Y-m-d H:i:s',CDateTimeParser::parse(date('Y-m-d',$startDate).' '.$startTime.':00:00','yyyy-MM-dd h:mm:ss'));
                    $resultArray[$val] = InstrumentDate::ENABLED_TRUE;
                }
            }
        }
        $unEnabledDateList = $model->unEnabledDate;
        foreach($unEnabledDateList as $elem)
        {
            $elem->start_time = date('H', strtotime($elem->start_date));
            $elem->end_time = date('H', strtotime($elem->end_date));
            $elem->start_date = date('Y-m-d', strtotime($elem->start_date));
            $elem->end_date = date('Y-m-d', strtotime($elem->end_date));

            $startDate = CDateTimeParser::parse($elem->start_date,'yyyy-MM-dd');
		    $endDate = CDateTimeParser::parse($elem->end_date,'yyyy-MM-dd');
            for(;$startDate <= $endDate;$startDate = strtotime("+ 1 days", $startDate))
            {
                $startTime = $elem->start_time;
                $startTime++;
                $startTime--;
                $endTime = $elem->end_time;;
                $endTime++;
                $endTime--;
                for(;$startTime != $endTime && $startTime < 24;$startTime++)
                {
                    $val = date('Y-m-d H:i:s',CDateTimeParser::parse(date('Y-m-d',$startDate).' '.$startTime.':00:00','yyyy-MM-dd h:mm:ss'));
                    $resultArray[$val] = InstrumentDate::ENABLED_FALSE;
                }
            }
        }
        return $resultArray;
    }
    /**
     * ===============================================================
     *                  生成预定时间表(综合所有因素)
     * ===============================================================
     */
    /**
     * 生成预定时间表
     * @args $id = instrument_id
     * @author : nonglei
     * @date   : 17/08/2014
     */
    public static function GenerateReserveDateTableByID($id)
    {
        $instrumentModel = Instrument::model()->findByPk($id);
        $isEnabledDateList = $instrumentModel->isEnabledDate;
        if(count($isEnabledDateList) == 0)
        {
            //没有可预约时间
            return null;
        }
        //最小可预约时间
        $minDate = CDateTimeParser::parse('2030-01-01 12','yyyy-MM-dd hh');
        $maxDate = 0;
        foreach($isEnabledDateList as $elem)
        {
		    $start = CDateTimeParser::parse($elem->start_date,'yyyy-MM-dd hh:mm:ss');
		    $end = CDateTimeParser::parse($elem->end_date,'yyyy-MM-dd hh:mm:ss');
            if($start < $minDate)
            {
                $minDate = $start;
            }
            if($end > $maxDate)
            {
                $maxDate = $end;
            }
        }
        $minDate = strtotime(date('Y-m-d', $minDate));
        $maxDate = strtotime(date('Y-m-d', $maxDate));
        //向昨天找到最近的星期天
        $backDay = date('w',$minDate);
        $minDate = strtotime("- {$backDay} days", $minDate);
        //向明天找最近的星期天
        $forwardDay = 7 - date('w', $maxDate);
        $maxDate = strtotime("+ {$forwardDay} days", $maxDate);

        //获取当前可预约的时间数组
        $IsEnabledArray = InstrumentDate::getIsEnabledDateArrayStatus($id);
        $weekarray=array("天","一","二","三","四","五","六");
        $dateTable = array();
        //一周一周的处理
        for(; $minDate != $maxDate; $minDate = strtotime("+ 1 days", $minDate))
        {
            $week = array();
            $week['start_date'] = date('Y-m-d', $minDate);
            $minDate = strtotime("+ 6 days", $minDate);
            $week['end_date'] = date('Y-m-d', $minDate);
            //一天一天的处理
            for($i = 0; $i < 7; $i++)
            {
                $day = array();
                $day['date'] = date('Y-m-d', strtotime("+ {$i} days", strtotime($week['start_date'])));
                $day['day'] = '星期'.$weekarray[date('w', strtotime($day['date']))];
                //一个小时一个小时的处理
                for($j = 0; $j < 24; $j++)
                {
                    $today = date('Y-m-d H:i:s', strtotime("+ {$j} hours", strtotime($day['date'])));
                    if(isset($IsEnabledArray[$today]) && $IsEnabledArray[$today] != -1)
                    {
                        array_push($day, $IsEnabledArray[$today]);
                    }
                    else
                    {
                        $num = -1;
                        array_push($day, $num);
                    }
                }
                array_push($week, $day);
            }
            array_push($dateTable, $week);
        }

        return $dateTable;
    }
    /**
     * 判断是否可以预约,用填表法
     * @args   : $id : instrument_id
     * @return : array('2014-08-17 22:00:00'=>x预约人数, '2014-08-17 22:00:00'=>-1不可预约)
     * @author : nonglei
     * @date   : 17/08/2014
     */
    public static function getIsEnabledDateArrayStatus($id)
    {
        $resultArray = array();
        $model = Instrument::model()->findByPk($id);
        $isEnabledDateList = $model->isEnabledDate;
        if(count($isEnabledDateList) == 0)
        {
            //没有可预约时间
            return $resultArray;
        }
        foreach($isEnabledDateList as $elem)
        {
            $elem->start_time = date('H', strtotime($elem->start_date));
            $elem->end_time = date('H', strtotime($elem->end_date));
            $elem->start_date = date('Y-m-d', strtotime($elem->start_date));
            $elem->end_date = date('Y-m-d', strtotime($elem->end_date));

            $startDate = CDateTimeParser::parse($elem->start_date,'yyyy-MM-dd');
		    $endDate = CDateTimeParser::parse($elem->end_date,'yyyy-MM-dd');
            for(;$startDate <= $endDate;$startDate = strtotime("+ 1 days", $startDate))
            {
                $startTime = $elem->start_time;
                $startTime++;
                $startTime--;
                $endTime = $elem->end_time;;
                $endTime++;
                $endTime--;
                for(;$startTime != $endTime && $startTime < 24;$startTime++)
                {
                    $formatDate = CDateTimeParser::parse(date('Y-m-d',$startDate).' '.$startTime.':00:00','yyyy-MM-dd h:mm:ss');
                    if($formatDate > strtotime('+ 2 hours', time()) && $startDate < strtotime("+ 2 weeks", time()))
                    {
                        $val = date('Y-m-d H:i:s',CDateTimeParser::parse(date('Y-m-d',$startDate).' '.$startTime.':00:00','yyyy-MM-dd h:mm:ss'));
                        $resultArray[$val] = 0;
                    }
                }
            }
        }
        $unEnabledDateList = $model->unEnabledDate;
        foreach($unEnabledDateList as $elem)
        {
            $startTime = $elem->start_time;
            $startTime++;
            $startTime--;
            $endTime = $elem->end_time;;
            $endTime++;
            $endTime--;
            for(;$startTime != $endTime && $startTime < 24;$startTime++)
            {
                $val = date('Y-m-d H:i:s',CDateTimeParser::parse(date('Y-m-d',$startDate).' '.$startTime.':00:00','yyyy-MM-dd h:mm:ss'));
                $resultArray[$val] = -1;
            }
        }
        $alreadyReserveLisr = $model->getReserveList();
        foreach($alreadyReserveLisr as $elem)
        {
            $start = date('Y-m-d H:i:s', CDateTimeParser::parse($elem->start_date,'yyyy-MM-dd hh:mm:ss'));
            if($resultArray[$start] != -1 && $resultArray[$start] != -2)
            {
                $resultArray[$start]++;
                if($elem->user->user_name == yii::app()->user->name)
                {
                    $resultArray[$start] = -2;
                }
            }
        }
        return $resultArray;
    }
}
